package com.usian.wemedia.filter;

import com.usian.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Fay
 * @date 2022/7/7&11:13
 */

/**
 * 获取用户id的过滤器
 */
@Slf4j
@Order(1)
@WebFilter(filterName = "userFilter",urlPatterns = "/api/*")
public class UserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    //获取请求头ServletRequest中没有获取请求头的方法需要强转为http
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String userId = httpServletRequest.getHeader("userId");
        log.info("请求头中的id为"+userId);
        if (!StringUtils.isEmpty(userId)){
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        chain.doFilter(request,response);
    }
}
